// src/VirtualScroll.js
import React, { useEffect, useRef, useState } from 'react';

const itemHeight = 30; // 每个项的高度
const totalItems = 10000; // 总项数
const buffer = 5; // 缓冲区，提前渲染的项数

const VirtualScroll = () => {
    const containerRef = useRef(null);
    const [visibleItems, setVisibleItems] = useState([]);

    const visibleItemsCount = Math.ceil(window.innerHeight / itemHeight) + buffer; // 可见项数加上缓冲区

    useEffect(() => {
        const handleScroll = () => {
            const scrollTop = containerRef.current.scrollTop; // 获取当前滚动位置
            const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - buffer); // 计算开始索引，减去缓冲区
            const endIndex = Math.min(startIndex + visibleItemsCount, totalItems); // 计算结束索引

            const items = [];
            for (let i = startIndex; i < endIndex; i++) {
                items.push(`Item ${i + 1}`);
            }
            setVisibleItems(items);
        };

        const container = containerRef.current;
        container.addEventListener('scroll', handleScroll);
        handleScroll(); // 初始渲染

        return () => {
            container.removeEventListener('scroll', handleScroll);
        };
    }, [visibleItemsCount]);

    return (
        <div
            ref={containerRef}
            style={{
                height: '400px', // 容器高度
                overflowY: 'auto', // 垂直滚动条
                border: '1px solid #ccc',
                position: 'relative',
            }}
        >
            <div style={{ height: `${totalItems * itemHeight}px`, position: 'relative' }}>
                {visibleItems.map((item, index) => (
                    <div key={index} style={{
                        height: `${itemHeight}px`,
                        display: 'flex',
                        alignItems: 'center',
                        padding: '0 10px',
                        boxSizing: 'border-box',
                        borderBottom: '1px solid #eee',
                    }}>
                        {item}
                    </div>
                ))}
            </div>
        </div>
    );
};

export default VirtualScroll;
